package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.service.UploadService;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.goods.NEWXIZAIAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class NEWJiZaiApiImpl implements NEWXIZAIAPI {

    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private UploadService uploadService;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    public static String createQQAccount() {
        int num = 8;
        String[] vec = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        num = num <= 0 ? 1 : num;
        StringBuffer str = new StringBuffer(10);
        for (int i = 0; i < num; i++) {
            int r1 = Long.valueOf(Math.round(Math.random() * (vec.length - 1))).intValue();
            str.append(vec[r1]);
        }
        return str.toString();
    }

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        goodsInfoAndAttrValueDto.setAccountNumber(createQQAccount());
        Map<String, Object> result = new HashMap<>();

        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner, "add");

        String path = "https://www.xizai.com/trade/goodsApi/parseingGameToApi";

        log.info("鸡仔添加接口请求参数={}", JSONObject.toJSONString(params));
        boolean flag = true;
        int count = 0;
        String response = "";
        while (flag) {
            response = HttpUtils.sendPost(path, JSONObject.toJSONString(params), "application/json");
            JSONObject resultJson = JSONObject.parseObject(response);
            String code = resultJson.getString("code");
            if (Objects.equals("147", code) && count <= 3) {
                flag = true;
            } else {
                flag = false;
            }
            count++;
        }
        log.info("鸡仔添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            result.put("outId", resultJson.getString("accountId"));
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner, "update");

        String path = "https://www.xizai.com/trade/goodsApi/updateAccountToApi";

        log.info("鸡仔编辑接口请求参数={}", JSONObject.toJSONString(params));
        boolean flag = true;
        int count = 0;
        String response = "";
        while (flag) {
            response = HttpUtils.sendPost(path, JSONObject.toJSONString(params), "application/json");
            JSONObject resultJson = JSONObject.parseObject(response);
            String code = resultJson.getString("code");
            if (Objects.equals("147", code) && count <= 3) {
                flag = true;
            } else {
                flag = false;
            }
            count++;
        }
        log.info("鸡仔编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        String path = "https://www.xizai.com/trade/goodsApi/offlineAccountByIdToApi";

        Map<String, Object> params = new HashMap<>();

        params.put("accountId", artRec.getOutid());
        params.put("phone", salePartner.getSaleKey());
        Map<String, Object> result = new HashMap<>();

        log.info("鸡仔删除接口请求参数={}", JSONObject.toJSONString(params));
        boolean flag = true;
        int count = 0;
        String response = "";
        while (flag) {
            response = HttpUtils.sendGet(path + "?phone=" + salePartner.getSaleKey() + "&accountId=" + artRec.getOutid(), null);
            JSONObject resultJson = JSONObject.parseObject(response);
            String code = resultJson.getString("code");
            if (Objects.equals("147", code) && count <= 3) {
                flag = true;
            } else {
                flag = false;
            }
            count++;
        }
        log.info("鸡仔删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner, String types) {
        GameAttribute gameAttribute = null;
        if (goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF16())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("和平精英")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("原神")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF20())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF4())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF4()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF7())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF7()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF10())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("地下城与勇士")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("逆战")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("使命召唤手游")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("永劫无间手游") || goodsInfoAndAttrValueDto.getGameName().contains("光遇") || goodsInfoAndAttrValueDto.getGameName().contains("永劫无间")) {

        } else if (goodsInfoAndAttrValueDto.getGameName().contains("金铲铲之战")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("无畏契约")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF1())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        } else if (goodsInfoAndAttrValueDto.getGameName().contains("暗区突围")) {
            if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF3())) {
                throw new GlobalException("实名不能为空!!!");
            }
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        } else {
            throw new GlobalException("当前游戏暂不支持");
        }
//        params.put("camp_id", an.substring(5,an.length()));
        Map<String, Object> params = new HashMap<>();
        params.put("accountOrigin", "1");
        params.put("aiPwd", "1");
        params.put("aiValue", goodsInfoAndAttrValueDto.getAccountNumber());
//        if(sa.getSaleKey().equals("15213450873")){
//            params.put("aiValue", goodsInfoAndAttrValueDto.getAccountNumber());
//        }else {
//            params.put("aiValue", UUIDGenerator.generate12());
//        }
        params.put("antiAddiction", "2");
//        String type = getType(goodsInfoAndAttrValueDto.getGameName());
//        if (StringUtils.isEmpty(type)) {
//            throw new GlobalException("暂不支持的游戏=" + goodsInfoAndAttrValueDto.getGameName());
//        }
//        params.put("categoryId", type);
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgUrls = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        String imgs = "";
        if (StringUtils.isNotEmpty(imgUrls)) {
            List<String> list = Arrays.asList(imgUrls.split(","));
            if (!CollectionUtils.isEmpty(list)) {
                for (String img : list) {
                    String imgurl = img;
//                    if (!pdhouzhui(imgurl)) {
//                        throw new GlobalException("附件图片的后缀或无后缀接口不支持");
//                    }
                    imgs = imgs + imgurl + ",";
                }
                imgs = imgs.substring(0, imgs.length() - 1);
            }
        } else {
            imgs = imgs + LCConstant.defaultImg;
        }
        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())) {
            imgs = goodsInfoAndAttrValueDto.getTitleImg() + "," + imgs;
        }
        params.put("imagel", imgs);
        if ("光遇,蛋仔派对,永劫无间,永劫无间手游".contains(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("isFace", "1");
        } else {
            if (gameAttribute.getFieldName().equals("可二次实名") || gameAttribute.getFieldName().equals("有修改人脸机会/实名是本人")
                    || gameAttribute.getFieldName().equals("有修改机会且实名是本人") || gameAttribute.getFieldName().equals("可修改实名")
                    || gameAttribute.getFieldName().equals("可改二次") || gameAttribute.getFieldName().equals("可实名")) {
                params.put("isFace", "1");
            } else {
                params.put("isFace", "0");
            }
        }
        params.put("name", goodsInfoAndAttrValueDto.getDes());
        params.put("price", goodsInfoAndAttrValueDto.getPrice());

        params.put("whetherAdult", "1");
        params.put("type", types);
        if (types.contains("update")) {
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if (!CollectionUtils.isEmpty(artRecs)) {
                ArtRec artRec = artRecs.get(0);
                params.put("accountId", artRec.getOutid());
            }
        } else {
            params.put("externalId", goodsInfoAndAttrValueDto.getId());
        }
        params.put("sallerContact", salePartner.getSaleKey());
        setOther(goodsInfoAndAttrValueDto, params, salePartner);
        return params;
    }

    public String formatImgUrl(String imgUrl) {
        if (imgUrl.contains("?")) {
            imgUrl = imgUrl.substring(0, imgUrl.indexOf("?"));
        }
        return imgUrl;
    }

    /**
     * 判断imgUrl里是否包含图片后缀
     *
     * @param str
     * @return
     */
    public boolean pdhouzhui(String str) {
        String image = str.substring(str.lastIndexOf(".") + 1).toLowerCase();
        String houzhui[] = {"jpeg", "jpg", "png", "gif", "webp", "bmp", "ico", ".tif"};
        return Arrays.asList(houzhui).contains(image);
    }

    private String toCoverImg(String imgUrl) {
        //1、判断图片是否存在.jpg 或者 .png  .JPG .PNGu
        //2、不存在开始解析上传七牛云
        //3、返回地址

        boolean b = false;
        String imgStr = cn.hutool.http.HttpUtil.get(imgUrl + "?imageInfo");
        JSONObject jsonObject = JSONObject.parseObject(imgStr);
        Long size = jsonObject.getLong("size");
        if (size < 50000000l) {
            b = true;
        }

        if (!(imgUrl.contains(".jpg") || imgUrl.contains(".png") || imgUrl.contains(".JPG") || imgUrl.contains(".PNG")) && StringUtils.isNotEmpty(imgUrl) || b) {
            URL url = null;
            try {
                url = new URL(imgUrl);
                BufferedImage image = ImageIO.read(url.openStream());
                byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
                return uploadService.upload2Qiniu(bytes, UUIDGenerator.generate() + ".jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return imgUrl;

    }

    /**
     * 开始匹配单选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param radioAttr
     */
    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, JSONObject gameJson, String radioAttr) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        String string = "";
        for (JSONObject object : jsonObjects) {
            String InterConfigId = object.getString("InterConfigId");
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    string = "";
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                String defaultValue = object.getString("defaultValue");
                                if (CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        gameJson.put(InterConfigId, defaultValue);
                                    }
                                }
                                if (!CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("InterConfigId");
                                    gameJson.put(InterConfigId, interConfigId2);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            String defaultValue = object.getString("defaultValue");
            interRadioReqs = object.getString("interRadioReqs");
            jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
            for (JSONObject objects : jsonObjects) {
                if (StringUtils.isNotEmpty(objects.getString("defaultValue"))) {
                    gameJson.put(defaultValue, objects.getString("defaultValue"));
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, JSONObject gameJson, String checkAttr) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            String pf_ids = "";
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);
                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            for (String s : split1) {
                                if (Objects.equals(s, ydConfigId1)) {
                                    String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                    pf_ids += "," + InterConfigId2;
                                }
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(pf_ids)) {
                gameJson.put(object.getString("id"), pf_ids.substring(1).trim());
            }
        }
    }

    /**
     * 开始匹配输入框属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param inputAttr
     */
    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, JSONObject gameJson, String inputAttr) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        String string = "";
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                string = "";
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            String oneValue = String.valueOf(o);
                            if (StringUtils.isNotEmpty(oneValue)) {
                                gameJson.put(object.getString("id"), oneValue);
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            String id = object.getString("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                gameJson.put(id, defaultValue);
            }
        }
    }

    private void setOther(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, SalePartner salePartner) {
        JSONObject gameJson = new JSONObject();
        //自动匹配属性
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_") + 1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        params.put("categoryId", interAttr.getInterGameId());
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, gameJson, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, gameJson, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, gameJson, interAttr.getInputAttr());

        if (Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("wzry_sys_area", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                gameJson.put("wzry_noble_rank", gameAttribute1.getFieldName());
            }
        }
        if (Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("hpjy_sys_area", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
        }
        if (Objects.equals("原神", goodsInfoAndAttrValueDto.getGameName())) {
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("游戏官方")) {
                gameJson.put("ys_sys_area", "官服");
            } else {
                gameJson.put("ys_sys_area", "B服");
            }
        }

        if (Objects.equals("枪战王者", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("cf_sys_area", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                gameJson.put("cf_vip", gameAttribute1.getFieldName());
            }

        }
        if (Objects.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("yxlm_kfd", "官服");//英雄联盟-客户端
            gameJson.put("yxlm_xyzhlx", "QQ");//英雄联盟-客户端
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getServerName())) {
                String fwq = "艾欧尼亚,比尔吉沃特,祖安,诺克萨斯,班德尔城,皮尔特沃夫,战争学院,巨神峰,黑色玫瑰,均衡教派,守望之海,征服之海,卡拉曼达,弗雷尔卓德,怒瑞玛,巨龙之巢,德玛西亚,无畏先锋,扭曲丛林,裁决之地,暗影岛,水晶之痕,影流,皮城警备,雷瑟守备,钢铁烈阳,教育网专区,男爵领域,峡谷之巅";
                List<String> collect = Arrays.asList(fwq.split(","));
                if (!CollectionUtils.isEmpty(collect)) {
                    if (collect.contains(goodsInfoAndAttrValueDto.getServerName())) {
                        gameJson.put("yxlm_fwq", goodsInfoAndAttrValueDto.getServerName());//英雄联盟-服务器
                    }
                }
            }
        }
        if (Objects.equals("穿越火线", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("cf_swin_sys_area", "官服");
            gameJson.put("cf_swin_war_zone", goodsInfoAndAttrValueDto.getGroupName());
            gameJson.put("cf_swin_war_zone_details", goodsInfoAndAttrValueDto.getServerName().replace("北方大区", "北方"));
        }
        if (Objects.equals("逆战", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("nz_sys_area", goodsInfoAndAttrValueDto.getGroupName().replace("区", ""));
        }
        if (Objects.equals("蛋仔派对", goodsInfoAndAttrValueDto.getGameName())) {
            if (goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                gameJson.put("dzpd_khd", "安卓官方");
            } else {
                gameJson.put("dzpd_khd", "苹果");
            }
        }
        if (Objects.equals("光遇", goodsInfoAndAttrValueDto.getGameName())) {
            if (goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                gameJson.put("gy_sys_area", "网易（安卓）");
            } else {
                gameJson.put("gy_sys_area", "网易（苹果）");
            }
        }
        if (Objects.equals("无畏契约", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("wwqy_khd", "WeGame");
        }
        if (Objects.equals("地下城与勇士", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("dnf_sys_area", "官服");
            String string = "{\"msg\":\"查询成功！具体返回见list\",\"code\":0,\"list\":[{\"value\":\"跨1\"},{\"value\":\"跨2\"},{\"value\":\"跨3A\"},{\"value\":\"跨3B\"},{\"value\":\"跨4\"},{\"value\":\"跨5\"},{\"value\":\"跨6\"},{\"value\":\"跨7A\"},{\"value\":\"跨7B\"},{\"value\":\"跨8\"}]}\n";
            String string1 = JSONObject.parseObject(string).getString("list");
            JSONArray jsonArray = JSONArray.parseArray(string1);
            for (Object o : jsonArray) {
                if (goodsInfoAndAttrValueDto.getGroupName().contains(JSONObject.parseObject(o.toString()).getString("value"))) {
                    gameJson.put("dnf_step", JSONObject.parseObject(o.toString()).getString("value"));
                    break;
                }
            }
        }
        if (Objects.equals("英雄联盟(手游)", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("lolm_sys_area", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
        }
        if (Objects.equals("永劫无间", goodsInfoAndAttrValueDto.getGameName())) {
            if (goodsInfoAndAttrValueDto.getGroupName().contains("网易")) {
                gameJson.put("yjwj_sys_area", "网易国服");
            } else if (goodsInfoAndAttrValueDto.getGroupName().contains("Steam")) {
                gameJson.put("yjwj_sys_area", "steam区");
            } else {
                gameJson.put("yjwj_sys_area", "epic渠道");
            }
            gameJson.put("yjwj_zh_type", goodsInfoAndAttrValueDto.getServerName().replace("网易", "").replace("帐", "账"));

        }
        if (Objects.equals("永劫无间手游", goodsInfoAndAttrValueDto.getGameName())) {
            //区服
            gameJson.put("yjwjsy_khd", goodsInfoAndAttrValueDto.getCarrierName());
            gameJson.put("yjwjsy_czxt", "安卓");
        }
        if (Objects.equals("金铲铲之战", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("jcczz_khd", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
        }
        if (Objects.equals("使命召唤手游", goodsInfoAndAttrValueDto.getGameName())) {
            //区服
            gameJson.put("smzh_sys_area", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName());
        }
        if (Objects.equals("暗区突围", goodsInfoAndAttrValueDto.getGameName())) {
            gameJson.put("aqtw_khd", goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName().replace("苹果", "ios"));
        }
        params.put("gameJson", gameJson);
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    //只保留中文
    private String onlyHanZi(String str) {
        String reg = "[^\u4e00-\u9fa5]";
        str = str.replaceAll(reg, "");
        return str;
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }


    private String getType(String type) {


        if (Objects.equals("王者荣耀", type)) {
            return "2";
        }

        if (Objects.equals("火影忍者", type)) {
            return "12";
        }
        if (Objects.equals("和平精英", type)) {
            return "26";
        }
        if (Objects.equals("原神", type)) {
            return "28";
        }
        if (Objects.equals("枪战王者", type)) {
            return "31";
        }
        if (Objects.equals("穿越火线", type)) {
            return "34";
        }
        if (Objects.equals("光遇", type)) {
            return "37";
        }
        if (Objects.equals("永劫无间", type)) {
            return "41";
        }
        if (Objects.equals("使命召唤手游", type)) {
            return "46";
        }
        if (Objects.equals("原神", type)) {
            return "28";
        }
        if (Objects.equals("英雄联盟", type)) {
            return "29";
        }
        if (Objects.equals("蛋仔派对", type)) {
            return "208";
        }
        if (Objects.equals("地下城与勇士", type)) {
            return "33";
        }
        if (Objects.equals("无畏契约", type)) {
            return "576";
        }
        if (Objects.equals("英雄联盟(手游)", type)) {
            return "38";
        }
        if (Objects.equals("金铲铲之战", type)) {
            return "45";
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, Object> param = new HashMap<>();
        String url = "https://www.xizai.com/trade/goodsApi/queryGameField";
        param.put("field_dict_type", "sys_hpjyRareAircraft");
        String response = getAtta("sys_yjwj_type");
//        String response = getAtta("aqtw_khd");
        log.info(response);
//        String time = new Date().getTime()+"";
//        log.info(time.substring(3,time.length()));
    }

    static String getAtta(String fieldDictType) {
        Map<String, Object> param = new HashMap<>();
        String url = "https://www.xizai.com/trade/goodsApi/queryGameField";
        param.put("field_dict_type", fieldDictType);
        String response = HttpUtils.doPostForm(url, param, null);
        return response;
    }

    static String dwStr = "[\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"青铜\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"白银\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"黄金\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"铂金\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"钻石\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"value\": \"战神\"\n" +
            "\t\t}\n" +
            "\t]";

    static String defDw = "value";
}

